function [trials,epoev] = cvc_eeg_epoch_to_edat_trial(EEG,evtype)
% CVC_EEG_EPOCHS_TO_EDAT_TRIALS
%
%  Synopsis
%  ========
%
%  [trials,epoev] = cvc_eeg_epoch_to_edat_trial(EEG)
%  trials         = cvc_eeg_epoch_to_edat_trial(EEG,evtype)
% 
%  -- Author: Mads Dyrholm --
%     Center for Visual Cognition, University of Copenhagen.
%     May 2011
%
%  Purpose
%  =======
%
%  Output
%  ======
%
%  Trials - A list of trial numbers, one per epoch.
%
%  epoev - The epoching event (has zero latency).
if nargin<2
  evtype = [];
end
if isempty(EEG.epoch)
  error('This dataset has no epoch structure.');
end
% 
trials = [];
epoev = [];
for epo=1:EEG.trials
  if isempty(evtype)
    % auto detect epoching evtype
    tmp = min(find([EEG.epoch(epo).eventlatency{:}]==0));
    tmp2 = EEG.epoch(epo).eventtype{tmp};
    if ~isnumeric(tmp2)
      tmp2 = str2num(tmp2);
    end
    epoev = cat(2,epoev,tmp2);
  else
    if isnumeric(evtype)
      evtype=num2str(evtype);
    end
    tmp = find(strcmp(EEG.epoch(epo).eventtype,evtype));
    if isempty(tmp) || EEG.epoch(epo).eventlatency{tmp}~=0
      trials = cat(2,trials,nan);
      continue
    end
  end
  trial = EEG.epoch(epo).eventtrial{tmp};
  trials = cat(2,trials,trial);
end
